package playermgr

import (
	"GameServer/common"
	"GameServer/common/beegomap"
	"GameServer/common/logger"
	"GameServer/db"
	"errors"
	"io/ioutil"
	_ "io/ioutil"
	"net/http"
	"strings"
	"sync"
	"time"
)

type DetectionType int

const (
	_ DetectionType = iota
)

var (
	players_map      *beegomap.BeeMap //= make(map[int]*common.GamePlayer)
	Players_map      *beegomap.BeeMap
	players_club     *beegomap.BeeMap
	players_alliance *beegomap.BeeMap
)

func init() {
	players_map = beegomap.NewBeeMap()
	Players_map = players_map
	players_club = beegomap.NewBeeMap()
	players_alliance = beegomap.NewBeeMap()
}

func GetPlayer(uid uint32) (*common.GamePlayer, common.ErrorType) {
	var player *common.GamePlayer = nil
	var err error
	for {
		player, err = GetPlayerFromMap(int(uid))
		if err == nil {
			return player, common.Error_OK
		}

		player, err = GetPlayerFromDB(int(uid))
		if err != nil {
			logger.Error("GetPlayer failed uid=%v err=%v", uid, err)
		}
		if player != nil && player.ConnLocker == nil {
			logger.Info("create player out channel uid:%v", uid)
			player.ConnLocker = new(sync.RWMutex)
			player.OutChannel = make(chan []byte, 32)
			player.OutDone = make(chan bool)
			player.LastAt = time.Now().Unix()
		}
		break
	}
	return player, common.Error_OK
}

func GetPlayerFromDB(uid int) (*common.GamePlayer, error) {
	player, err := db.LoadPlayerFromDB(uid)
	if err != nil {
		logger.Info("load from db error:%v for uid:%v", err, uid)
		return nil, err
	}

	players_map.Set(uint32(uid), player)
	logger.Info("GetPlayerFromDB-players_map.Set uid :%v,player:%+v", uid, *player)

	return player, nil
}

func GetPlayerFromMap(uid int) (*common.GamePlayer, error) {
	vv := players_map.Get(uint32(uid))
	if vv != nil {
		player, _ := vv.(*common.GamePlayer)
		return player, nil
	}
	return nil, errors.New("not found uid")
}

//func IsOnline(uid int) (bool, net.Conn) {
//	vv := players_map.Get(uint32(uid))
//	if vv != nil {
//		player, _ := vv.(*common.GamePlayer)
//		if player != nil {
//			return true, player.Conn
//		}
//	}
//	return false, nil
//}

func RemovePlayer(uid int) bool {
	players_map.Delete(uint32(uid))
	logger.Info("RemovePlayer players_map.Delete uid:%v", uid)
	return true
}

func uidArrToStr(uidArr []uint32) string {
	uidStr := make([]string, 0)
	for _, uid := range uidArr {
		if uid > 0 {
			uidStr = append(uidStr, common.Itoa(int(uid)))
		}
	}
	return strings.Join(uidStr, ",")
}

type ClubChangeResp struct {
	MsgCode    int    `json:"msg_code"`
	Status     int    `json:"status"`
	Msg        string `json:"msg"`
	ServerTime int    `json:"server_time"`
}

//进行http请求
func DoHttpSend(url string) (string, error) {
	res, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return "", err
	}
	return string(body), nil
}
